package com.potato369.cryptEureka.controller;

import com.potato369.cryptEureka.common.api.CommonResult;
import com.potato369.cryptEureka.domain.Admin;
import com.potato369.cryptEureka.domain.Permission;
import com.potato369.cryptEureka.dto.AdminLoginParam;
import com.potato369.cryptEureka.service.AdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 后台用户管理
 * Created by macro on 2018/4/26.
 */

@Api(tags = "UmsAdminController", description = "后端用户管理")
@RestController
@RequestMapping("/admin")
public class UmsAdminController {

    private AdminService adminService;

    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @ApiOperation(value = "用户注册")
    @PostMapping(value = "/register")
    public CommonResult<?> register(@RequestBody Admin umsAdminParam, BindingResult result) {
        if (result.hasErrors() && !Objects.isNull(result.getFieldError())) {
            return CommonResult.failed(result.getFieldError().getDefaultMessage());
        }
        Admin umsAdmin = this.adminService.register(umsAdminParam);
        if (umsAdmin == null) {
            CommonResult.failed();
        }
        return CommonResult.success(umsAdmin);
    }

    @ApiOperation(value = "登录以后返回token")
    @PostMapping(value = "/login")
    public CommonResult<?> login(@RequestBody AdminLoginParam umsAdminLoginParam, BindingResult result) {
        if (result.hasErrors() && !Objects.isNull(result.getFieldError())) {
            return CommonResult.failed(result.getFieldError().getDefaultMessage());
        }
        String token = this.adminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
        if (token == null) {
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @ApiOperation("获取用户所有权限（包括+-权限）")
    @GetMapping(value = "/permission/{adminId}")
    public CommonResult<?> getPermissionList(@PathVariable Long adminId) {
        List<Permission> permissionList = this.adminService.getPermissionList(adminId);
        return CommonResult.success(permissionList);
    }
}
